package netty;

import global.Global;
import global.InitCache;
import handler.MsgDecoder;
import handler.MsgHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import report.MsgReportCenter;

/**
 * Netty客户端启动
 *
 * @author zhouwz
 * @date 2020/11/3 14:10
 */
public class Client {

    public static void startNettyClient() {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(boosGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(new MsgDecoder(), new MsgHandler());
                        }
                    });
            bootstrap.localAddress(InitCache.nettyClientIp, InitCache.nettyClientPort);
            ChannelFuture channelFuture = bootstrap.connect(InitCache.nettyServerIp, Global.NETTY_SERVER_PORT).sync();
            // 报文上报中心
            MsgReportCenter.doReport(channelFuture.channel());
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            boosGroup.shutdownGracefully();
        }
    }
}
